/*
 * @Description: 场所拥挤程度
 * @Author: zy
 * @Date: 2021-04-21 16:22:21
 * @LastEditors: zy
 * @LastEditTime: 2021-04-21 19:34:27
 */
import * as d3 from 'd3'
export class Crowd {
  chart = {}
  constructor (divId) {
    this.divId = divId
  }

  initChart () {
    this.chart.padding = {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
    this.chart.divHeight = document.getElementById(this.divId).offsetHeight -
      this.chart.padding.top -
      this.chart.padding.bottom
    this.chart.divWidth = document.getElementById(this.divId).offsetWidth -
      this.chart.padding.left -
      this.chart.padding.right

    this.chart.svg = d3
      .select('#' + this.divId)
      .append('svg')
      .attr('width', this.chart.divWidth +
        this.chart.padding.left +
        this.chart.padding.right
      )
      .attr('height', this.chart.divHeight +
        this.chart.padding.top +
        this.chart.padding.bottom
      )
      .attr('class', 'svg_chart')
  }

  render (data) {
    this.initChart()
    this.chart.itemWidth = this.chart.divWidth / 3
    this.chart.itemHeight = this.chart.divHeight / 6

    let extent = d3.extent(data, function (d) {
      return d.num
    })

    let colorDomain = d3.extent(data, function (d) {
      return d.density
    })

    let rScale = d3.scaleLinear()
      .domain(extent)
      .range([5, Math.min(this.chart.itemWidth, this.chart.itemHeight) / 2])

    let colorScale = d3.scaleLinear()
      .domain(colorDomain)
      .range(['green', 'red'])

    let crowd = this.chart.svg.append('g')
      .attr('class', 'crowds')

    let items = crowd.selectAll('.item')
      .data(data)
      .enter()
      .append('g')
      .attr('class', 'item')

    items.append('circle')
      .attr('cx', (_, i) => {
        return this.chart.itemWidth / 2 + (i % 3) * this.chart.itemWidth
      })
      .attr('cy', (_, i) => {
        return this.chart.itemHeight / 2 + Math.floor(i / 3) * this.chart.itemHeight
      })
      .attr('r', d => rScale(d.num))
      .style('fill', d => colorScale(d.density))
      .style('stroke', 'black')
      .style('opcaity', 0.6)

    items.append('text')
      .attr('x', (_, i) => {
        return this.chart.itemWidth * 0.3 + (i % 3) * this.chart.itemWidth
      })
      .attr('y', (_, i) => {
        return this.chart.itemHeight + Math.floor(i / 3) * this.chart.itemHeight
      })
      .text(d => d.area)
  }
}
